<script setup lang="ts" name="ExtensionPropertyAddEdit">
import { mapState } from 'pinia'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { addExtensionProperty, editExtensionProperty } from '../../../utils/extension'

const mapStates = computed(() => {
  return mapState(useModelerStore, ['getActive'])
})

const AddEditFormRef = ref(null)

const visible = ref(false)
const title = ref('')
const editIndex = ref(-1)
const formData = ref({
  name: '',
  value: ''
})
const rules = ref({
  name: { required: true, message: '属性名称不能为空', trigger: ['blur', 'change'] },
  value: { required: true, message: '属性值不能为空', trigger: ['blur', 'change'] }
})
// 显示新建/编辑部门弹窗
const showDialog = (v) => {
  visible.value = true
  if (v) {
    title.value = '编辑属性'
    formData.value.name = v.row.name
    formData.value.value = v.row.value
    editIndex.value = v.index
  } else {
    title.value = '添加属性'
    editIndex.value = -1
  }
}
// 子组件将方法暴露给父组件
defineExpose({ showDialog })
const closeDialog = () => {
  formData.value.name = ''
  formData.value.value = ''
  if (AddEditFormRef.value) {
    AddEditFormRef.value.clearValidate()
  }
  visible.value = false
}

const handleOk = () => {
  console.log(formData.value)
  if (!AddEditFormRef.value) return false
  AddEditFormRef.value.validate((valid) => {
    if (valid) {
      const result: any = {}
      result.name = formData.value.name
      result.value = formData.value.value
      if (editIndex.value > -1) {
        editExtensionProperty(mapStates.value.getActive(), formData.value, editIndex.value)
      } else {
        addExtensionProperty(mapStates.value.getActive(), formData.value)
      }
      closeDialog()
    }
  })
}
</script>

<template>
  <el-dialog v-model="visible" width="600px" append-to-body destroy-on-close :title="title">
    <el-form ref="AddEditFormRef" label-width="auto" label-position="right" :model="formData" :rules="rules">
      <el-form-item label="属性名称" prop="name">
        <el-input v-model="formData.name" clearable placeholder="请输入属性名称" />
      </el-form-item>
      <el-form-item label="属性值" prop="value">
        <el-input v-model="formData.value" clearable placeholder="请输入属性值" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="modal-footer" ref="modalFooter">
        <el-button @click="closeDialog">{{ $t('buttons.buttonCancel') }}</el-button>
        <el-button type="primary" @click="handleOk">{{ $t('buttons.buttonConfirm') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-form {
  padding: 40px 80px;
}

.modal-footer {
  display: inline-flex;
  overflow: hidden;
}
</style>
